<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8"%>
<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>客户订单</title>
    <jsp:include page="../cssList.jsp" flush="true"/>
  </head>

  <body class="hold-transition sidebar-mini">
    <div class="wrapper">

      <jsp:include page="../topMenu.jsp" flush="true"/>
      <jsp:include page="../leftMenu.jsp" flush="true"/>

      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">

        <!-- Content Header (Page header) -->
        <div class="content-header">
          <div class="container-fluid">
            <div class="row mb-2">
              <div class="col-sm-6">
                <h1>订单列表</h1>
              </div>
              <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                  <li class="breadcrumb-item"><a href="#">首页</a></li>
                  <li class="breadcrumb-item active">客户订单</li>
                  <li type="button" class="btn btn-block btn-success" data-toggle="modal" data-target="#newOrderModal">创建新订单</li>
                </ol>
              </div>
            </div>
          </div>
        </div>

        <!-- Main content 最新订单列表 -->
        <section class="content">
          <div class="row">
            <div class="col-12">
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title">客户订单</h3>
                </div>
                <div class="card-body">
                  <table id="example2" class="table table-bordered table-hover">

                    <thead>
                      <tr>
                        <th>序号</th><th>订单号</th><th>商品编号</th><th>商品单价</th><th>订单总价</th><th>重量</th><th>备注</th><th>订单状态</th><th>下单时间</th><th>操作</th>
                      </tr>
                    </thead>

                    <tbody id="ordersList">

                      <%--<tr>--%>
                        <%--<td>1</td><td>10001</td><td>InternetExplorer 4.0</td><td>Win 95+</td><td> 4</td><td>X</td><td>Trident</td><td>InternetExplorer 4.0</td><td>Win 95+</td><td> 4</td>--%>
                        <%--<td>--%>
                          <%--<a class="btn btn-app" data-toggle="modal" data-target="#myModal"><i class="fa fa-edit"></i> 修改</a>--%>
                          <%--<a class="btn btn-app"><i class="fa fa-inbox"></i> 删除</a>--%>
                        <%--</td>--%>
                      <%--</tr>--%>

                      <%--<tr>--%>
                        <%--<td>2</td><td>10002</td><td>InternetExplorer 4.0</td><td>Win 95+</td><td> 4</td><td>X</td><td>Trident</td><td>InternetExplorer 4.0</td><td>Win 95+</td><td> 4</td>--%>
                        <%--<td>--%>
                          <%--<a class="btn btn-app" data-toggle="modal" data-target="#myModal"><i class="fa fa-edit"></i> 修改</a>--%>
                          <%--<a class="btn btn-app"><i class="fa fa-inbox"></i> 删除</a>--%>
                        <%--</td>--%>
                      <%--</tr>--%>

                    </tbody>

                  </table>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- 模态框（Modal)开始-->
        <div class="modal" id="newOrderModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog" style="max-width:65%;">
            <div class="modal-content" style="margin:auto;">
            <div class="modal-header">
              <h4 class="modal-title" id="newOrderModalLabel">
                新订单
              </h4>
            </div>
            <div class="modal-body">

              <form role="form">

                <table id="allGoodsListTable" class="table table-bordered table-hover">

                  <thead>
                  <tr>
                    <th>商品名称</th><th>商品编号</th><th>样本图</th><th>规格</th><th>单价</th><th>库存</th><th>重量</th><th>选择</th>
                  </tr>
                  </thead>

                  <tbody id="allGoodsListTbody">

                  </tbody>

                </table>

              </form>

            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">取消
              </button>
              <button onclick="createNewOrder();" type="button" class="btn btn-primary">
                保存提交
              </button>
            </div>
          </div><!-- /.modal-content -->
          </div>
        </div>
        <!-- 模态框（Modal)结束-->

      </div>

      <jsp:include page="../bottomRightsInfo.jsp" flush="true"/>
    </div>
    <!-- ./wrapper -->

    <jsp:include page="../scriptList.jsp" flush="true"/>

    <script>
        $(function () {
            //生成订单列表,默认显示最新的10个
            generateOrderList();
            //将后台传递的商品数据转换为模态框表html
            generateGoodsModel();
            //暂时只知道这个能处理checkbox
            processCheckbox();
        });

        var newOrderGoodsNumber = [];
        var newOrderGoodsWeight = [];
        var remark = '';
        function createNewOrder(){
          //在提交之前,查看所有的class为iCheck-helper的checkbox,如果发现他们的付标签有'checked' class,那么就根据对应的input子元素的id(商品编号)来获取对应的商品数量.
          // 并且判断此商品数量是否大于此商品库存量,如果没问题就放入newOrderGoodsWeight , newOrderGoodsNumber对象中

          getNewOrderGoodsArray();
          //通过ajax发给后台解析,后台依然需要验证库存.
            console.log(newOrderGoodsWeight);
            console.log(newOrderGoodsNumber + ' , 长度是:' + newOrderGoodsNumber.length);
            remark = $('#remark').val();
          $.ajax({
              type: "POST",
              url: "${pageContext.request.contextPath}/createNewOrderAjax", //请求URL地址
              dataType: "text", //服务器返回数据类型
              cache:false,  //防止浏览器使用缓存,一般针对IE
              traditional: true,  //如果传递数组, 则要设置此属性
              data: {newOrderGoodsNumber: newOrderGoodsNumber, newOrderGoodsWeight: newOrderGoodsWeight, remark:remark},
              success: function(data){  //请求成功回调方法
                  if(data === "ok"){
                      //如果创建订单成功,就刷新订单页面
                      console.log("订单创建成功!准备刷新页面...");
                      window.location.href="${pageContext.request.contextPath}/dataTablePage";
                  } else {
                      alert(data);
                  }
              },
              error: function(){alert("创建订单失败!请看日志.")}, //请求失败回调方法
              waitMsg : '正在处理数据....'
          });
         }

        //根据checkbox获取本次订单已选择的所有商品的编号和对应数量的信息
        function getNewOrderGoodsArray(){
          var allCheckedCheckBoxFromModel = $("[class='icheckbox_minimal-blue checked']");
          var checkedGoodsNumber,checkedGoodsWeight,checkedGoodsStock;
          var index = 0;
            for(var i=0;i<allCheckedCheckBoxFromModel.length;i++){
                checkedGoodsNumber = $(allCheckedCheckBoxFromModel[i]).children('input').attr("id");
                checkedGoodsWeight = parseFloat($('#goodsWeight' + checkedGoodsNumber).val()).toFixed(2);
                checkedGoodsStock = parseFloat($('#goodsStock' + checkedGoodsNumber).html().trim());
                if(isNaN(checkedGoodsWeight)){
                    console.log('请输入正确的数量!');
                    $('#goodsWeight' + checkedGoodsNumber).val('');
                } else if(checkedGoodsWeight > checkedGoodsStock){
                    console.log('不允许比库存量大!');
                    $('#goodsWeight' + checkedGoodsNumber).val('');
                } else if(checkedGoodsWeight <= 0){
                    console.log('请输入正确格式的数量');
                    $('#goodsWeight' + checkedGoodsNumber).val('');
                } else {
                    console.log('OK');
                    newOrderGoodsWeight[index] = checkedGoodsWeight;
                    newOrderGoodsNumber[index] = checkedGoodsNumber;
                    index ++;
                }
            }
        }

        function generateOrderList(){
          var allOrder = [] , allOrderJS = [];
            <c:forEach items="${allOrder}" var="item">
              <c:if test="${!empty item}">
                allOrder.push('${item}');
              </c:if>
            </c:forEach>
            var allOrderListHTML = '';
            $('#ordersList').html('');
            if(allOrder.length > 0){
                for(index in allOrder){
                    if(!$.isEmptyObject(allOrder[index])){
                        allOrderJS[index] = JSON.parse(allOrder[index]);
                        var order = allOrderJS[index];
                        var no = ++index;
                        var createTime = new Date(order.createTime).format("yyyy-MM-dd hh:mm:ss");
                        allOrderListHTML = allOrderListHTML +  '<tr><td>' + no + '</td><td>' + order.number + '</td><td>' + order.goodsNumber + '</td><td>' + order.goodsPrice + '<span> (元/公斤)</span></td><td>' + order.orderPrice + '<span> (元)</span></td><td>' + order.weight + '<span> (公斤)</span></td></td><td>' + order.remark + '</td></td><td>' + order.status + '</td><td>' + createTime + '</td>' +
                            '<td><a class="btn btn-app" data-toggle="modal" data-target="#myModal"><i class="fa fa-edit"></i> 修改</a><a class="btn btn-app"><i class="fa fa-inbox"></i> 删除</a></td></tr>';
                    }
                 }
            }
        $('#ordersList').html(allOrderListHTML);
        }

function generateGoodsModel(){
//JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
//$.parseJSON 其实就是 JSON.parse();
//$.isEmptyObject(object)   这是jquery的对象判空方法
var allGoods = [];
var allGoodsJS = [];
<c:forEach items="${allGoods}" var="item">
<c:if test="${!empty item}">
allGoods.push('${item}');
</c:if>
</c:forEach>

//var goodsNameArray = [];goodsImageArray = [];goodsTypeArray = [];goodsPriceArray = [];goodsRemarkArray = [];goodsStockArray = [];
var allGoodsListHTML = '';
//先清空模态框
$('#allGoodsListTbody').html(allGoodsListHTML);
if(allGoods.length > 0){
for(index in allGoods){
if(!$.isEmptyObject(allGoods[index])){
allGoodsJS[index] = JSON.parse(allGoods[index]);
var goods = allGoodsJS[index];
//JS会自动为这个checkbox增加一段小代码包裹住这个input , 不需要懂原理,麻烦...
allGoodsListHTML = allGoodsListHTML +  '<tr><td>' + goods.name + '</td><td>' + goods.number + '</td><td>' + goods.img + '</td><td>' + goods.type + '</td><td>' + goods.price + '<span> (元/公斤)</span></td><td id="goodsStock' + goods.number + '">' + goods.stock + '<span> (公斤)</span></td>' +
  '<td><input maxlength="10"  onkeyup="value=value.replace(/[^0-9\.]/,\'\')" id="goodsWeight' +  goods.number + '"><span> (公斤)</span></td>' +
  '<td><div><input id="' + goods.number + '" type="checkbox" class="minimal"  style="position: absolute; opacity: 0;"></div></td></tr>';
}
}
allGoodsListHTML = allGoodsListHTML + '<tr><td colspan=\'8\'><span> 客户姓名 : </span><div style="display:inline"><input id="clientName" maxlength="10"></div><span> 联系电话 : </span>' +
'<div style="display:inline"><input id="clientPhone" maxlength="18" onkeyup="value=value.replace(/[^0-9]/,\'\')"></div><span> 订单备注 : </span><div style="display:inline"><input id="remark" maxlength="100"></div></td></tr>';
}

$('#allGoodsListTbody').html(allGoodsListHTML);
}

//ajax 修改订单操作
/* $("#login").click(function(){
var account = $("#account").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "",
dataType: "text",                                         //服务器返回数据类型
cache:false,                                              //防止浏览器使用缓存,一般针对IE
data: {account: account, password: password},             //请求参数
success: function(data){
if(data === "ok"){
window.location.href="/indexPage";
} else {
alert(data);
}
},                                                      //请求成功回调方法
error: function(){alert("error!")}                           //请求失败回调方法
})
});*/


//      $(function () {
//        $("#example1").DataTable();
//        $('#example2').DataTable({
//          "paging": true,
//          "lengthChange": false,
//          "searching": false,
//          "ordering": true,
//          "info": true,
//          "autoWidth": false
//        });
//      });


function processCheckbox(){
//Initialize Select2 Elements
$('.select2').select2();

//Datemask dd/mm/yyyy
$('#datemask').inputmask('dd/mm/yyyy', { 'placeholder': 'dd/mm/yyyy' });
//Datemask2 mm/dd/yyyy
$('#datemask2').inputmask('mm/dd/yyyy', { 'placeholder': 'mm/dd/yyyy' });
//Money Euro
$('[data-mask]').inputmask();

//Date range picker
$('#reservation').daterangepicker();
//Date range picker with time picker
$('#reservationtime').daterangepicker({
timePicker         : true,
timePickerIncrement: 30,
format             : 'MM/DD/YYYY h:mm A'
});
//Date range as a button
$('#daterange-btn').daterangepicker(
{
ranges   : {
'Today'       : [moment(), moment()],
'Yesterday'   : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days' : [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month'  : [moment().startOf('month'), moment().endOf('month')],
'Last Month'  : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate  : moment()
},
function (start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'))
}
);

//iCheck for checkbox and radio inputs
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass   : 'iradio_minimal-blue'
});
//Red color scheme for iCheck
$('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
checkboxClass: 'icheckbox_minimal-red',
radioClass   : 'iradio_minimal-red'
});
//Flat red color scheme for iCheck
$('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
checkboxClass: 'icheckbox_flat-green',
radioClass   : 'iradio_flat-green'
});

//Colorpicker
$('.my-colorpicker1').colorpicker();
//color picker with addon
$('.my-colorpicker2').colorpicker();

//Timepicker
$('.timepicker').timepicker({
showInputs: false
});
}

//为Date增加一个format方法
        Date.prototype.format = function(format)
        {
            var o = {
                "M+" : this.getMonth()+1, //month
                "d+" : this.getDate(),    //day
                "h+" : this.getHours(),   //hour
                "m+" : this.getMinutes(), //minute
                "s+" : this.getSeconds(), //second
                "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
                "S" : this.getMilliseconds() //millisecond
            }
            if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
                (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            for(var k in o)if(new RegExp("("+ k +")").test(format))
                format = format.replace(RegExp.$1,
                    RegExp.$1.length==1 ? o[k] :
                        ("00"+ o[k]).substr((""+ o[k]).length));
            return format;
        }
</script>

</body>
</html>
